var createError = require('http-errors');
var express = require('express');
const { NotFoundError } = require("./utils/error")
const session = require("express-session")

var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');


// 默认读取的项目更目录下的.env环境变量文件,注意使用顺序
require("dotenv").config()

require("express-async-errors")

// 实例创建

var app = express();



// 数据库连接
require("./dao/init")


// 日志

app.use(logger('dev'));

// json格式
app.use(express.json());



/**
 * 可以将流的数据转换
 */
app.use(express.urlencoded({ extended: false }));


app.use(session({
    secret: process.env.SESSION_SERCET,
    resave: true,
    saveUninitialized: true
}))

// 引入cookie
app.use(cookieParser());

// 静态资源
app.use(express.static(path.join(__dirname, 'public')));





// 验证token
app.use(require("./utils/tokenMiddleware"))

// 引入路由

// 用户
app.use("/api/admin", require("./routes/admin"))

// 验证码
app.use("/res/captcha", require("./routes/vcode"))


// 首页
app.use("/api/banner", require("./routes/banner"))

// 上传图片
app.use("/api/upload", require("./routes/upload"))

// 分类
app.use("/api/blogtype", require("./routes/blogType"))

// 博客
app.use("/api/blog", require("./routes/blog"))

// 项目
app.use("/api/project", require("./routes/demo"))

// 评论
app.use('/api/message', require("./routes/message"));

// 全局设置
app.use('/api/setting', require("./routes/setting"));

// 关于我
app.use('/api/about', require("./routes/about"));


// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});

// error handler {错误处理}
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    if (err.name === "NotFoundError") {
        res.send(new NotFoundError().toResponseJSONError())
    }
    // render the error page
    // res.status(err.status || 500);
    // res.render('error');
});

module.exports = app;